<template>
    <div class="product-form-wrapper">
        <div class="product-form">
          <h2>{{ isEdit ? '编辑商品' : '新增商品' }}</h2>
          
          <form @submit.prevent="handleSubmit">
            <!-- 商品标题 -->
            <div class="form-item">
              <label for="title">商品标题:</label>
              <input type="text" id="title" v-model="item.Title" required />
            </div>
            
            <!-- 商品描述 -->
            <div class="form-item" >
              <label for="introduce">商品描述:</label>
              <textarea id="introduce" v-model="item.Introduce" required style="height:100px"></textarea>
            </div>
            
    
            <!-- 商品首页图片 -->
            <div class="form-item">
              <label for="images">商品首页图片:</label>
              <input type="text" id="images" v-model="item.Images" />
            </div>
            
            <!-- 商品价格 -->
            <div class="form-item">
              <label for="price">商品价格:</label>
              <input type="text" id="price" v-model="item.Price" required />
            </div>
            
             <!-- 商品内容 -->
             <div class="form-item">
                <label for="content">商品内容:</label>
                <textarea id="content" v-model="item.Content" required style="height:500px"></textarea>
              </div>

            <div class="form-item">
            <label for="content">修改密码:</label>
            <input type="text" id="password" v-model="password" />
            </div>

            <!-- 提交按钮 -->
            <button type="submit" class="submit-btn">{{ isEdit ? '更新商品' : '新增商品' }}</button>
          </form>
        </div>
        <div class="container">
            <h2>文件上传</h2>
            <input type="file" id="fileInput" />
            <button @click="uploadFile()">上传文件</button>
            <button @click="refreshFile()" style="margin-left: 10px;">刷新文件</button>
            <div class="message" id="message"></div>
            <div class="container" style="margin-top: 10px;height:400px">
                <iframe ref="iframe" src="/files/uploads/" style="height:400px;width:100%"></iframe> 
            </div>
        </div>
        
      </div>
   
  </template>
  
  <script setup>
  import { ref, onMounted } from "vue";
  import { useRoute, useRouter } from 'vue-router';
  import axios from 'axios';
  import { addItem, getItemById, upItemById } from "../services/api";
  
  const password = ref("");
  const route = useRoute();
  const router = useRouter();
  const iframe = ref(null);

  const isEdit = ref(false); // 判断是新增还是编辑
  const item = ref({
    ItemId: null,
    Title: '',
    Introduce: '',
    Content: '',
    Images: '',
    Video: '',
    Price: ''
  });
  
  onMounted(() => {
    // 如果是编辑商品，获取商品数据
    if (route.params.id) {
        if(route.params.id != -1){
            isEdit.value = true;
            fetchProduct(route.params.id);
        }
    }
  });
  
  const fetchProduct = async (id) => {
    try {
      const res = await getItemById(id)
      item.value = res;
    } catch (error) {
      console.error('Error fetching product data:', error);
    }
  };
  
  const handleSubmit = async () => {
    try {
        var res = "123"
      if (isEdit.value) {
        // 更新商品
        res = await upItemById(`${item.value.ItemId}`, item.value, password.value);
        console.log(res)
      } else {
        // 新增商品
        res = await addItem(item.value, password.value)
        console.log(res)
      }
      // 提交成功后跳转到商品列表页面
      alert(res)
    } catch (error) {
       console.error('Error submitting form:', error);
    }
  };

  const  uploadFile = () =>  {
    const fileInput = document.getElementById('fileInput');
    const messageElement = document.getElementById('message');

    // 检查文件是否选择
    if (!fileInput.files || fileInput.files.length === 0) {
        messageElement.textContent = '请先选择一个文件！';
        messageElement.style.color = 'red';
        return;
    }

    const formData = new FormData();
    formData.append('file', fileInput.files[0]);

    // 发送上传请求
    fetch('/upload', {
        method: 'POST',
        body: formData,
    })
    .then(response => response.json())
    .then(data => {
        if (data.filePath) {
            messageElement.textContent = `文件上传成功！文件路径: ${data.filePath}`;
            messageElement.style.color = 'green';
        } else {
            messageElement.textContent = '文件上传失败！';
            messageElement.style.color = 'red';
        }
    })
    .catch(error => {
        messageElement.textContent = '上传过程中发生错误！';
        messageElement.style.color = 'red';
    });
}
  const refreshFile = ()=>{
    // 重新设置 iframe 的 src 属性，强制刷新
    const src = iframe.value.src;
    iframe.value.src = '';
    iframe.value.src = src;
}

  </script>
<style scoped>
.product-form-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: aliceblue;
  background-size: cover;
}

.product-form {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  width: 60%;
  max-width: 800px;
}

h2 {
  text-align: center;
  margin-bottom: 20px;
}

.form-item {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
  color: #333;
}

input,
textarea {
  width: 100%;
  padding: 12px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}

textarea {
  resize: vertical;
  height: 150px;
}

.submit-btn {
  background-color: #4CAF50;
  color: white;
  padding: 12px 20px;
  font-size: 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  width: 100%;
  transition: background-color 0.3s;
}

.submit-btn:hover {
  background-color: #45a049;
}

@media (max-width: 768px) {
  .product-form {
    width: 80%;
  }
}

.container {
    margin-left: 20px;
    background-color: white;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    text-align: center;
}

h2 {
    margin-bottom: 20px;
}

input[type="file"] {
    margin-bottom: 20px;
}

button {
    background-color: #007bff;
    color: white;
    padding: 10px 20px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

    button:hover {
        background-color: #0056b3;
    }

.message {
    margin-top: 20px;
    font-size: 14px;
}
</style>